import axios, { type AxiosResponse, type AxiosError } from 'axios'
import { message } from 'ant-design-vue'
import type { ApiResponse } from '@/types'

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.DEV ? '' : (import.meta.env.VITE_API_BASE_URL || 'http://localhost:9999'),
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    
    // 从localStorage获取token
    const token = localStorage.getItem('token')

    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 直接返回response，让调用方处理业务逻辑
    if(!response.data.success){
      message.error(response.data.message)
    }
    return response
  },
  (error: AxiosError) => {
    // HTTP错误处理
    const { response } = error
    const status = response?.status
    
    switch (status) {
      case 401:
        message.error('未授权，请重新登录')
        // 清除token并跳转到登录页
        clearLocalCache()
        window.location.href = '/login'
        break
      case 403:
        message.error('权限不足，无法访问')
        break
      case 404:
        message.error('请求的资源不存在')
        break
      case 500:
        message.error('服务器内部错误')
        break
      case 502:
        message.error('网关错误')
        break
      case 503:
        message.error('服务不可用')
        clearLocalCache()
        window.location.href = '/login'
        break
      case 504:
        message.error('网关超时')
        break
      default:
        if (error.code === 'ECONNABORTED') {
          message.error('请求超时，请稍后重试')
        } else if (error.message?.includes('Network Error')) {
          message.error('网络连接失败，请检查网络')
        } else {
          message.error(error.message || '网络错误，请稍后重试')
        }
    }
    
    return Promise.reject(error)
  }
)

// API封装函数
export const api = {
  get: <T = any>(url: string, params?: any): Promise<ApiResponse<T>> => {
    return request.get(url, { params }).then(res => res.data)
  },
  
  post: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return request.post(url, data).then(res => res.data)
  },
  
  put: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return request.put(url, data).then(res => res.data)
  },
  
  delete: <T = any>(url: string): Promise<ApiResponse<T>> => {
    return request.delete(url).then(res => res.data)
  }
}

const clearLocalCache = () => {
  localStorage.removeItem('user_permissions_cache')
  localStorage.removeItem('dynamic_routes_cache')
  localStorage.removeItem('routes_initialized')
  localStorage.removeItem('token')
}

export default request 